#include <stdio.h>
#include "somb.h"
#include <unistd.h>

void run_mem_server_method_service_provider(uint32_t handle,uint32_t ServiceId,void*MthReqData,uint32_t MthReqDataLen)
{
    //printf("run_mem_server recv ServiceId=%08x handle=%08x datalen=%d\n",ServiceId,handle,MthReqDataLen);
}
int32_t run_mem_server_event_on_listen_cb(uint32_t ServiceId,void**EvtData,uint32_t *EvtDataLen)
{
    /*if this function is called, that means some other consumer was listenning to BASICCOM_SID_EVENT_TEST*/
    //printf("test2 recv Event ServiceId=0x%08x was being listened \n", ServiceId);
    //
    /* prepare the memory space for the event data */
    *EvtData = SOMB_ALLOC(32);
    if(NULL == *EvtData)
    {
        printf("### malloc failed\n");
        return SOMB_FAIL;
    }
    memset(*EvtData, 0, 32);

    /* prepare the event data */
    *EvtDataLen = sprintf((char *)*EvtData, "%08x is ready!", ServiceId);

    /*don't free the memory allocated by EvtData if return SOMB_OK, it will auto freed by somb*/
    return SOMB_OK;
}

int32_t deploy_service(int service_num)
{
    void**Instance = NULL;
    Instance = vSOMB_Service_Instance_New();
    if(NULL == Instance)
    {
        printf("new service instance failed");
        return -1;
    }


    int ret = 0;
    uint32_t service_id = 0;

    for(int loop=0; loop < service_num; loop++)
    {
        service_id = loop;

        if (loop%2 == 0) 
        { 
            ret = i32SOMB_Service_Add(Instance, service_id, SOMB_SVC_TYPE_METHOD,run_mem_server_method_service_provider); 
        } 
        else 
        { 
            ret = i32SOMB_Service_Add(Instance, service_id, SOMB_SVC_TYPE_EVENT,run_mem_server_event_on_listen_cb); 
        }

        if(SOMB_OK != ret)
        {
            printf("somb add service(%08x) failed\n", loop);
        }
    }

    ret = i32SOMB_Service_Instance_Deploy(Instance);
    if(SOMB_OK != ret)
    {
        printf("test2 server somb service deploy failed\n");
        return -1;
    }
    else 
    {
        printf("test2 server somb service deploy success\n");
    }


    ret = i32SOMB_Service_Instance_Destroy(Instance);
    if(SOMB_OK != ret)
    {
        printf("somb service destory failed\n");
        return -1;
    }

    return 0;
}

int main(void)
{
    uint32_t SubNsId;
    int32_t ret = i32SOMB_SubNs_Init(&SubNsId);
    if(SOMB_OK != ret)
    {
        printf("%s somb sub ns init failed\n",__FUNCTION__ );
        return -1;
    }
    printf("SubNs=%d SOMB Init success\n",SubNsId);


    int service_num;
    scanf("%d",&service_num);
    printf("your service is %d \n",service_num);
    deploy_service(service_num);

    while (1)
    {
        sleep(1);
    }

    return 0;
}
